package com.jprocms.module.cms.controller.portal.api;

import com.jpro.framework.common.pojo.CommonResult;
import com.jpro.framework.common.pojo.PageResult;
import com.jpro.framework.security.core.LoginUser;
import com.jpro.framework.security.core.util.SecurityFrameworkUtils;
import com.jpro.module.system.api.user.AdminUserApi;
import com.jpro.module.system.api.user.dto.MemberUserRespDTO;
import com.jprocms.module.cms.controller.admin.guestbook.vo.GuestbookFrontPostReqVO;
import com.jprocms.module.cms.controller.admin.guestbook.vo.GuestbookPageReqVO;
import com.jprocms.module.cms.controller.admin.guestbook.vo.GuestbookQueryListReqVO;
import com.jprocms.module.cms.controller.admin.guestbook.vo.GuestbookRespVO;
import com.jprocms.module.cms.convert.guestbook.GuestbookConvert;
import com.jprocms.module.cms.dal.dataobject.guestbook.GuestbookDO;
import com.jprocms.module.cms.dal.dataobject.site.SiteDO;
import com.jprocms.module.cms.enums.EnumGuestbookStatus;
import com.jprocms.module.cms.service.guestbook.GuestbookService;
import com.jprocms.module.cms.util.CmsContextUtil;
import com.jprocms.module.cms.util.RequestUtils;
import com.xingyuv.captcha.model.common.ResponseModel;
import com.xingyuv.captcha.model.vo.CaptchaVO;
import com.xingyuv.captcha.service.CaptchaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.jpro.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.jpro.framework.common.pojo.CommonResult.success;
import static com.jprocms.module.cms.constant.CmsSysConstants.*;
import static com.jprocms.module.cms.enums.ErrorCodeConstants.*;

/**
 * 留言 Controller
 *
 * @author jprocms
 */
@Tag(name = "留言接口", description = "留言接口")
@RestController
@RequestMapping({FRONT_API + "/guestbook"})
public class GuestbookApiController {
    private CaptchaService captchaService;
    private final GuestbookService service;
    private final AdminUserApi adminUserApi;

    public GuestbookApiController(CaptchaService captchaService,
                                  GuestbookService service,
                                  AdminUserApi adminUserApi) {
        this.captchaService = captchaService;
        this.service = service;
        this.adminUserApi = adminUserApi;
    }

    @Operation(summary = "获取留言列表（GuestbookList标签）")
    @GetMapping
    public CommonResult<List<GuestbookRespVO>> list(GuestbookQueryListReqVO reqVO, HttpServletRequest request) {
        if (reqVO.getSiteId() == null) {
            reqVO.setSiteId(CmsContextUtil.getCurrSiteId());
        }
        if (reqVO.getCount() > CMS_LIST_MAX_COUNT) {
            reqVO.setCount(CMS_LIST_MAX_COUNT);
        }
        reqVO.setStatus(EnumGuestbookStatus.CHECKED.getStatus());
        final List<GuestbookDO> guestbookList = service.getGuestbookList(reqVO);
        final List<GuestbookRespVO> guestbookRespVOS = GuestbookConvert.INSTANCE.convertList(guestbookList);
        return success(guestbookRespVOS);
    }

    @Operation(summary = "获取留言分页（GuestbookPage标签）")
    @GetMapping("/page")
    public CommonResult<PageResult<GuestbookRespVO>> page(GuestbookPageReqVO reqVO, HttpServletRequest request) {
        if (reqVO.getSiteId() == null) {
            reqVO.setSiteId(CmsContextUtil.getCurrSiteId());
        }
        if (reqVO.getPageSize() > CMS_LIST_MAX_COUNT) {
            reqVO.setPageSize(CMS_LIST_MAX_COUNT);
        }
        reqVO.setStatus(EnumGuestbookStatus.CHECKED.getStatus());
        final PageResult<GuestbookDO> guestbookPage = service.getGuestbookPage(reqVO);
        final PageResult<GuestbookRespVO> guestbookRespVOPageResult = GuestbookConvert.INSTANCE.convertPage(guestbookPage);
        return success(guestbookRespVOPageResult);
    }

    @Operation(summary = "获取留言详情")
    @ApiResponses(value = {@ApiResponse(description = "获取留言详情")})
    @GetMapping("/{id:[\\d]+}")
    public CommonResult<GuestbookRespVO> show(@Parameter(description = "留言详情ID") @PathVariable Long id) {
        GuestbookDO bean = service.getGuestbook(id);
        if (bean == null) {
            throw exception(GUESTBOOK_NOT_EXISTS);
        }
        if (!bean.getSite().getSiteConfig().getGuestbook().getIsOpen()) {
            throw exception(GUESTBOOK_NOT_ENABLE);
        }
        return CommonResult.success(GuestbookConvert.INSTANCE.convert(bean));
    }

    @Operation(summary = "提交留言")
    @PostMapping
    public CommonResult<Boolean> post(@RequestBody GuestbookFrontPostReqVO guestbookCreateReqVO,
                                      HttpServletRequest request) {
        SiteDO site = CmsContextUtil.getSite();
        if (!site.getSiteConfig().getGuestbook().getIsOpen()) {
            throw exception(GUESTBOOK_NOT_ENABLE);
        }
        final LoginUser user = SecurityFrameworkUtils.getLoginUser();
        Long userId;
        String username = ANONYMOUS_USER_NAME;
        String nickname = ANONYMOUS_USER_NAME;
        if (user == null) {
            if (site.getSiteConfig().getGuestbook().getNeedLogin()) {
                throw exception(PORTAL_USER_NOT_LOGIN);
            }
            userId = ANONYMOUS_USER_ID;
        } else {
            userId = user.getId();
            final CommonResult<MemberUserRespDTO> userQueryResult = adminUserApi.getMember(userId);
            if (userQueryResult.isSuccess()) {
                username = userQueryResult.getData().getUsername();
                nickname = userQueryResult.getData().getNickname();
            }
        }
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaVerification(guestbookCreateReqVO.getCaptchaVerification());
        ResponseModel response = captchaService.verification(captchaVO);
        // 验证不通过
        if (!response.isSuccess()) {
            throw exception(CAPTCHA_PARAM_ERROR, response.getRepMsg());
        }
        guestbookCreateReqVO.setSiteId(site.getId());
        String ip = RequestUtils.getRemoteAddr(request);
        guestbookCreateReqVO.setMsgIp(ip);
        guestbookCreateReqVO.setUserId(userId);
        guestbookCreateReqVO.setUsername(username);
        guestbookCreateReqVO.setNickname(nickname);
        guestbookCreateReqVO.setStatus(EnumGuestbookStatus.TO_CHECK.getStatus());
        service.createGuestbook(guestbookCreateReqVO);
        return CommonResult.success(true);
    }

}
